import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import {ToolsService} from "@shared/service/tools/tools.service";
import {ParentService} from "@train/parent/parent.service";
import {ActivatedRoute, Params} from "@angular/router";
import {AuthService} from "@shared/service/auth/auth.service";
import {
  TrainSchoolCourseListScheduleVo, TrainSchoolCourseScheduleVo
} from "@interface/index";

@Component({
  selector: 'seed-parent-schedule-list',
  templateUrl: './schedule.component.html',
  styleUrls: ['./schedule.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class TrainScheduleComponent implements OnInit {
  public isSearching = false;
  public params = {
    studentId: '',
    orgUserId: '',
    beginTimeStamp: 0,
    endTimeStamp: 0
  };
  public hasLoadData = false;
  public chooseNum: number;
  public scheduleData: TrainSchoolCourseListScheduleVo[] = [];
  public weekData = new Array(7);
  public startTime: Date;
  public endTime: Date;
  public day = 3600 * 24;
  public weekTime: Date[] = [];
  public weekText = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  public showData: TrainSchoolCourseScheduleVo[] = [];
  public today: Date;
  constructor(
    private tools: ToolsService,
    private parentSer: ParentService,
    private route: ActivatedRoute,
    private authSer: AuthService
  ) {
    this.tools.setTitle('课程表');
    this.today = new Date();
    this.params.orgUserId = this.authSer.getAuthOrgId();
    // this.params.orgUserId = 'seedp20141';
    this.route.params.subscribe((params: Params) => {
      this.params.studentId = params['studentId'];
    });
  }

  /**
   * @desc 初始化
   * @author ouxh
   * @time 2018/1/26
   */
  initData() {
    const week = this.tools.getRankTime('week');
    this.startTime = week[0];
    this.endTime = week[1];
    this.fetchListData(0);
  }
  /**
   * @desc 请求
   * @author ouxh
   * @time 2018/1/29
   * @param {number} i 往前或往后的周数 -2 -1 0 1 ...
   */
  fetchListData(i: number) {
    this.upDateWeekInfo(i);
    this.isSearching = true;
    this.tools.showLoading();
    this.parentSer.findScheduleList(this.params)
      .subscribe(res => {
        this.isSearching = false;
        this.tools.hideLoading();
        if (res.result === '0') {
          this.scheduleData = res.data;
          this.handleResp();
          this.setDefaultData();
          if (!this.hasLoadData) {
            this.hasLoadData = true;
          }
        }else {
          this.tools.showToast(res.msg);
        }
      });
  }

  /**
   * @desc 选择某天
   * @author ouxh
   * @time 2018/1/26
   * @param {number} i
   */
  chooseDay(i: number) {
    this.chooseNum = i;
    this.showData = this.weekData[i] ? this.weekData[i] : [];
  }

  /**
   * @desc 判断是否今天
   * @param {Date} day
   * @author ouxh
   * @time 2018/1/26
   * @returns {boolean}
   */
  isToday(day: Date): boolean {
    const today = new Date();
    if (day.getFullYear() === today.getFullYear()
      && day.getMonth() === today.getMonth()
      && day.getDate() === today.getDate()
    ) {
      return true;
    }else {
      return false;
    }
  }
  /**
   * @desc 更新周信息（startTime 、 endTime、 params）
   * @author ouxh
   * @time 2018/1/26
   * @param {number} i 表示往前或者往后的多少周
   */
  upDateWeekInfo(i: number) {
    this.chooseNum = -1;
    this.startTime = this.tools.nextDay(this.startTime, i * 7);
    this.endTime = this.tools.nextDay(this.endTime, i * 7);
    // this.params.beginTimeStamp = this.startTime.getTime();
    // this.params.endTimeStamp = this.endTime.getTime();
    this.params.beginTimeStamp = this.getMaxTimeStamp(this.startTime);
    this.params.endTimeStamp = this.getMaxTimeStamp(this.endTime, false);
    for (let j = 0; j < 7; j++) {
      this.weekTime[j] = this.tools.nextDay(this.startTime, j);
      if (this.isToday(this.weekTime[j])) {
        this.chooseNum = j;
      }
    }
  }

  /**
   * 获取零点时间戳
   * @param {Date} time
   * @param {boolean} isZero true：0:0:0，false : 23:59:59
   * @returns {number}
   */
  getMaxTimeStamp(time: Date, isZero: boolean = true) {
    if (isZero) {
      time.setHours(0);
      time.setMinutes(0);
      time.setSeconds(0);
    }else {
      time.setHours(23);
      time.setMinutes(59);
      time.setSeconds(59);
    }
    return time.getTime();
  }
  /**
   * @desc 更新周信息（startTime 、 endTime、 params）
   * @author ouxh
   */
  setDefaultData() {
    if (this.chooseNum >= 0) {
      this.showData = this.weekData[this.chooseNum] ? this.weekData[this.chooseNum] : [];
    }else {
      this.chooseNum = 3;
      this.showData = this.weekData[3] ? this.weekData[3] : [];
    }
  }
  /**
   * @desc 切换周
   * @param {number} i
   */
  nextWeek(i: number) {
    if (this.isSearching) {
      return;
    }
    this.fetchListData(i);
  }

  /**
   * @desc 选择某天
   * @author ouxh
   * @time 2018/1/26
   */
  handleResp() {
    const weekData = [];
    this.scheduleData.forEach(eachTime => {
      eachTime.weekList.forEach(each => {
        if (each.courseList && each.courseList.length > 0) {
          if (!weekData[each.weekCode - 1]) {
            weekData[each.weekCode - 1] = [];
          }
          each.courseList.forEach(eachCourse => {
            weekData[each.weekCode - 1].push(eachCourse);
          });
        }
      });
    });
    this.weekData = weekData;
  }

  /**
   * @desc 判断是否标红
   * @author ouxh
   * @time 2018/2/6
   * @param {number} time
   * @param {string} unit
   */
  isWarn(time: number, unit: string) {
    if (unit === '天' && time < 30) {
      return true;
    } else if (unit === '次' && time < 10) {
      return true;
    } else {
      return false;
    }
  }
  ngOnInit() {
    this.initData();
  }

}
